import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:myapp/pages/hot_key/hot_key_vm.dart';
import 'package:myapp/pages/search/search_page.dart';
import 'package:myapp/repository/datas/common_website_data.dart';
import 'package:myapp/repository/datas/search_hot_keys_data.dart';
import 'package:myapp/route/route_utils.dart';
import 'package:provider/provider.dart';
import 'package:webview_flutter/webview_flutter.dart';

import '../../common_ui/web/webview_page.dart';
import '../../common_ui/web/webview_widget.dart';
import '../../route/routes.dart';
import '../web_view_page.dart';

class HotKeyPage extends StatefulWidget {
  const HotKeyPage({super.key});

  @override
  State createState() {
    return _HotKeyPageState();
  }
}

///常用网站item回调
typedef WebsiteClick = Function(String name,String link);

class _HotKeyPageState extends State<HotKeyPage> {
  HotKeyViewModel viewModel = HotKeyViewModel();


  @override
  void initState() {
    super.initState();
    viewModel.initData();
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) {
        return viewModel;
      },
      child: Scaffold(
        body: SafeArea(
          child: SingleChildScrollView(
            child: Expanded(
              child: Column(
                children: [
                  //标题
                  Container(
                    height: 45.h,
                    decoration: BoxDecoration(
                      border: Border(
                        top: BorderSide(width: 0.5.r, color: Colors.grey),
                        bottom: BorderSide(width: 0.5.r, color: Colors.grey))),
                    padding: EdgeInsets.only(left: 20.w,right: 20.w),
                    child: Row(children: [
                        Text( "搜索热词", style: TextStyle( fontSize: 14.sp,color: Colors.black)),
                        Expanded(child: SizedBox()),
                        GestureDetector(
                          onTap: (){
                            //进入搜索页面
                            RouteUtils.push(context,const SearchPage());
                          },
                          child: Image.asset("assets/images/icon_search.png",width: 30.r,height: 30.r),
                        )
                      ],
                    ),
                  ),
                  //搜索热词列表
                  Consumer<HotKeyViewModel>(
                    builder: (context, vm, child) {
                      return _gridView(false,keyList: vm.keyList,itemTap: (value){
                        //进入搜索页面
                        RouteUtils.push(context, SearchPage(keyword: value,));
                      });
                    },
                  ),
                  //常用网站标题
                  Container(
                    height: 45.h,
                    alignment: Alignment.centerLeft,
                    decoration: BoxDecoration(
                        border: Border(
                            top: BorderSide(width: 0.5.r, color: Colors.grey),
                            bottom: BorderSide(width: 0.5.r, color: Colors.grey))),
                    margin: EdgeInsets.only(top: 20.h),
                    padding: EdgeInsets.only(left: 20.w,right: 20.w),
                    child: Text( "常用网站", style: TextStyle( fontSize: 14.sp,color: Colors.black))
                    ),
                  //常用网站
                  Consumer<HotKeyViewModel>(
                    builder: (context, vm, child) {
                      return _gridView(true,websiteList: vm.websiteList,webSiteClick: (name,link){
                        RouteUtils.push(context, WebViewPage(loadResource: link, webViewType: WebViewType.URL
                          ,title:name,showTitle: true,));
                      });
                    },
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }


  //isWebsite 判断是否为常用网站,true 传入 websiteList，否 传入  keyList
  /// itemTap 事件相应函数
  Widget _gridView(bool? isWebsite,{List<CommonWebsiteData>? websiteList,List<SearchHotKeysData>? keyList,ValueChanged<String>? itemTap,WebsiteClick? webSiteClick}){
    return Container(
        margin: EdgeInsets.only(top: 20.h),
        padding: EdgeInsets.symmetric(horizontal: 20.w),
        child: GridView.builder(
          physics: NeverScrollableScrollPhysics(),
          shrinkWrap: true,
          gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
              //主轴的间隔
              mainAxisSpacing: 8.r,
              //最大横轴范围
              maxCrossAxisExtent: 120.w,
              //宽高比
              childAspectRatio: 3,
              crossAxisSpacing: 8.r
          ),
          itemBuilder: (context, index) {
            //常用网站
            if (isWebsite == true){
              return _item(name: websiteList?[index].name,link: websiteList?[index].link,webSiteClick: webSiteClick);
            }else{
              return _item(name: keyList?[index].name, itemTap:itemTap);
            }

          },
          itemCount: isWebsite == true ? websiteList?.length ?? 0 : keyList?.length ?? 0,
        ));
  }

  Widget _item({String? name,ValueChanged<String>? itemTap,String? link,WebsiteClick? webSiteClick}){
    return GestureDetector(onTap: (){
      //webSite
      if(link !=null){
        webSiteClick?.call(name ?? "",link);
      }else{
        itemTap?.call(name??"");
      }
    },child: Container(
      alignment: Alignment.center,
      decoration: BoxDecoration(
          border: Border.all(color: Colors.grey,width: 0.5.r),
          borderRadius: BorderRadius.all(Radius.circular(10.r))
      ),
      child: Text(name ?? ""),
    ));
  }
}
